<template>
  <div class="app-container">
    <!-- 条件搜索 -->
    <div class="filter-container">
      <el-form ref="queryForm" :model="listQuery.param" size="small" :inline="true" label-width="auto">
        <el-form-item label="流程定义" prop="procDefKey">
          <flow-proc-key v-model="listQuery.param.procDefKey" placeholder="流程定义" style="width: 100%;" class="filter-item" @change="handleFilterQuery" />
        </el-form-item>
        <el-form-item label="流程实例ID" prop="procInstId">
          <el-input v-model="listQuery.param.procInstId" placeholder="流程实例ID" class="filter-item" @keyup.enter.native="handleFilterQuery" />
        </el-form-item>
        <el-form-item label="业务流水号" prop="bizKey">
          <el-input v-model="listQuery.param.bizKey" placeholder="业务流水号" class="filter-item" @keyup.enter.native="handleFilterQuery" />
        </el-form-item>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilterQuery">
          搜索
        </el-button>
        <el-button v-waves class="filter-item" icon="el-icon-refresh-right" @click="handleRestQuery">
          重置
        </el-button>
      </el-form>
    </div>
    <div class="filter-container">
      <div style="float: right;">
        <el-button icon="el-icon-refresh" circle @click="handleFilterQuery" />
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :key="tableKey"
      v-loading="loading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      scrollbar-always-on="true"
    >
      <el-table-column type="selection" width="50px" align="center" />
      <el-table-column label="序号" type="index" width="50px" align="center" />
      <el-table-column label="流程实例ID" min-width="120px" align="left">
        <template v-slot="{row}">
          <span>{{ row.procInstId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="业务流水号" min-width="120px" align="left">
        <template v-slot="{row}">
          <span>{{ row.bizKey }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" width="160px" align="left">
        <template v-slot="{row}">
          <span>{{ row.startTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="持续时间（s）" min-width="90px" align="left">
        <template v-slot="{row}">
          <span>{{ row.duration / 1000 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程名称" min-width="130px" align="left">
        <template v-slot="{row}">
          <span>{{ row.procDefName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程发起人" min-width="85px" align="left">
        <template v-slot="{row}">
          <span>{{ convertUser(row.startUserId, users) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程状态" min-width="90px" align="left">
        <template v-slot="{row}">
          <el-tag v-if="row.businessStatus === 'success'" type="success">审批通过</el-tag>
          <el-tag v-else-if="row.businessStatus === 'refuse'" type="danger">审批拒绝</el-tag>
          <el-tag v-else-if="row.businessStatus === 'running'">正在审批</el-tag>
          <el-tag v-else-if="row.businessStatus === 'reject'" type="warning">审批驳回</el-tag>
          <el-tag v-else-if="row.businessStatus === 'waiting'">等待审批</el-tag>
          <el-tag v-else-if="row.businessStatus === 'cancel'" type="info">流程撤回</el-tag>
          <el-tag v-else-if="row.businessStatus === 'delete'" type="warning">流程作废</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="流程定义ID" min-width="200px" align="left">
        <template v-slot="{row}">
          <span>{{ row.procDefId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160px" class-name="small-padding fixed-width">
        <template v-slot="{row,$index}">
          <el-button size="mini" type="info" icon="el-icon-document" @click="handleDetail(row, $index)">详情</el-button>
          <el-dropdown style="margin-left: 10px;" @command="handleClick($event, row, $index)">
            <el-button size="mini" type="primary">更多
              <i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu>
              <el-dropdown-item v-permission="permission.assign" command="assign"><i class="el-icon-user"> 指派</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.delegate" command="delegate"><i class="el-icon-connection"> 委派</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.cancel" command="cancel"><i class="el-icon-document-remove"> 撤回</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.del" command="del"><i class="el-icon-delete"> 删除</i></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格分页 -->
    <pagination :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="handleInit" />

    <!-- 详情页面 -->
    <el-drawer
      :visible.sync="visible"
      direction="rtl"
      size="50%"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :show-close="false"
    >
      <template v-slot:title>
        <div class="drawer-header">
          <span>详情</span>
          <div>
            <el-button icon="el-icon-close" @click="handleClose">
              取消
            </el-button>
          </div>
        </div>
      </template>
      <el-tabs v-model="activeName" style="height: 450px;">
        <el-tab-pane label="流转记录" name="first">
          <flow-task-his :param="procInstId" />
        </el-tab-pane>
        <el-tab-pane label="流程信息" name="second">
          <instance-diagram :param="procInstId" />
        </el-tab-pane>
      </el-tabs>
    </el-drawer>

    <!-- 用户选择器组件 -->
    <flow-instance-task ref="instTask" :params="task" />
  </div>
</template>

<script>
import { handlePageList } from './api'
import { handleDelete, handleCancel } from '@/views/flow/api/instance'
import { handleDelegate, handleAssign } from '@/views/flow/api/task'
import { handleGetAllUserList } from '@/views/sys/userInfo/api'
import permission from '@/directive/permission/index' // 权限判断指令
// import checkPermission from '@/utils/permission' // 权限判断函数
import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
import { convertUser } from '@/utils'
import Pagination from '@/components/Pagination'
import FlowInstanceTask from './task.vue'
import FlowTaskHis from '../components/TaskHis/index.vue'
import InstanceDiagram from '../components/InstDiagram/index.vue'
import FlowProcKey from '@/views/flow/components/ProcessKey/index.vue'

export default {
  // 当前页面名称（组件）
  name: 'FlowInstance',
  // 引用组件
  components: { FlowProcKey, Pagination, FlowTaskHis, InstanceDiagram, FlowInstanceTask },
  directives: { permission, waves },
  filters: {},
  data() {
    return {
      // 列表table的key
      tableKey: 0,
      // 遮罩层
      loading: true,
      // table数据对象
      list: [],
      // 总条数
      total: 0,
      // table条件查询对象
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        // sort: '+id',
        param: {
          procDefKey: undefined,
          procInstId: undefined,
          procDefId: undefined,
          bizKey: undefined
        }
      },
      // 表单数据对象
      formData: {},
      // 是否显示弹出层
      visible: false,
      // 弹出层状态值（新增和修改共用同一个表单页面）
      state: '',
      // 弹出层标题
      title: {
        update: '修改',
        create: '新增',
        detail: '详情'
      },
      // 权限标识
      permission: {
        assign: ['flow:inst:assign'],
        delegate: ['flow:inst:delegate'],
        cancel: ['flow:inst:cancel'],
        del: ['flow:inst:del']
      },
      // 表单校验规则
      rules: {},
      activeName: 'first',
      imageLoading: false,
      imageUrl: undefined,
      procInstId: undefined,
      users: [],
      task: {
        opType: undefined,
        procInstId: undefined,
        visible: false
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.handleInit()
    handleGetAllUserList().then(res => {
      this.users = res.data
    })
  },
  mounted() {},
  methods: {
    convertUser,
    // 查询table数据对象
    handleInit() {
      this.loading = true
      handlePageList(this.listQuery).then(res => {
        this.list = res.data
        if (res.total) {
          this.total = Number(res.total)
        }
        this.loading = false
      })
    },
    // 条件查询table数据
    handleFilterQuery() {
      this.listQuery.pageNum = 1
      this.handleInit()
    },
    // 重置table查询条件
    handleRestQuery() {
      this.$refs.queryForm.resetFields()
    },
    // 更多点击操作项
    handleClick(item, row, index) {
      this.opType = item
      this.opRow = row
      // 委派
      // 指派
      if (item === 'delegate' || item === 'assign') {
        this.task.opType = item
        this.task.procInstId = row.procInstId
        this.task.visible = true
        this.$nextTick(() => {
          this.$refs['instTask'].handleInit()
        })
      }
      // 删除
      if (item === 'del') {
        this.handleDelete(row, index)
      }
      // 撤回
      if (item === 'cancel') {
        this.handleCancel(row, index)
      }
    },
    // 详情
    handleDetail(row) {
      this.procInstId = row.procInstId
      this.visible = true
    },
    // 委派
    handleDelegate(row, index) {
      this.task.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 指派
    handleAssign(row, index) {
      this.$refs.userSelector.open()
    },
    // 获取选中的用户
    handleUserSelector(data) {
      console.log(this.opRow)
      // 委派
      if (this.opType === 'delegate') {
        handleDelegate({ taskId: this.opRow.taskId, assignee: data.userId }).then((res) => {
          //  刷新table
          this.handleFilterQuery()
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
            duration: 4000
          })
        })
      }
      // 指派
      if (this.opType === 'assign') {
        handleAssign({ taskId: this.opRow.taskId, assignee: data.userId }).then((res) => {
          //  刷新table
          this.handleFilterQuery()
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
            duration: 4000
          })
        })
      }
    },
    // 删除
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 显示加载遮罩
        const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
        handleDelete({ procInstId: row.procInstId, reason: '删除流程' }).then((res) => {
          loading.close()
          //  刷新table
          this.handleFilterQuery()
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
            duration: 4000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 撤回
    handleCancel(row, index) {
      handleCancel({ procInstId: row.procInstId }).then((res) => {
        //  刷新table
        this.handleFilterQuery()
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success',
          duration: 4000
        })
      })
    },
    // 关闭弹出层
    handleClose() {
      this.visible = false
      this.activeName = 'first'
    }
  }
}
</script>
